package com.kezhou.kezhoucloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kezhou.kezhoucloud.components.HttpUtils;
import com.kezhou.kezhoucloud.entity.AccountSt;
import com.kezhou.kezhoucloud.entity.TmpInfo;
import com.kezhou.kezhoucloud.mapper.KeZhouMapper;
import com.kezhou.kezhoucloud.service.KeZhouService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class KeZhouServiceImpl implements KeZhouService {
    @Autowired
    KeZhouMapper km;

    //api-登录 6-未注册 7-密码错误 10-服务器问题 13-登陆成功
    @Override
    public int signInCheck(String tryPhoneNum, String tryPassword) {
        try {
            List<AccountSt> accountStList = km.getAllAccountsByPhone(tryPhoneNum);
            if (accountStList.size()<1){
                return 6;
            }
            if (accountStList.get(0).getPasswordDetail().equals(tryPassword)){
                return 13;
            }else {
                return 7;
            }
        }catch (Exception e){
            return 10;
        }
    }

    //api-发送验证码
    @Override
    public boolean getPhoneCode(String phoneNum, int mode) {
        //生成6位验证码
        String verificationCode = generateVerificationCode(6);
        // 创建一个 VerificationInfo 对象并设置手机号、验证码和模式
        TmpInfo info = new TmpInfo();
        info.setPhoneNumber(phoneNum);
        info.setVerificationCode(verificationCode);
        info.setMode(phoneNum+mode);
        // 将 VerificationInfo 对象转换为 JSON 字符串
        String jsonInfo = JSON.toJSONString(info);

        if (sendCode(phoneNum,verificationCode)){
            try {
                // 连接 Redis
                Jedis jedis = new Jedis("localhost", 6379);
                // 将信息存储到 Redis 中，使用mode作为键
                jedis.setex(info.getMode(), 120, jsonInfo);
                // 关闭 Redis 连接
                jedis.close();
                return true;
            }catch (Exception e){
                System.out.println(e);
                return false;
            }
        }
        return false;
    }
    //生成随机验证码
    public static String generateVerificationCode(int length) {
        String numbers = "0123456789"; // 可供选择的字符集合

        Random random = new Random();
        StringBuilder code = new StringBuilder(length);

        for (int i = 0; i < length; i++) {
            int randomIndex = random.nextInt(numbers.length());
            code.append(numbers.charAt(randomIndex));
        }
        return code.toString();
    }
    //发送验证码
    private boolean sendCode(String phoneNum, String code){
        String host = "https://gyytz.market.alicloudapi.com";
        String path = "/sms/smsSend";
        String method = "POST";
        String appcode = " 3d65f8435f184453bc65d9269585e979";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phoneNum);
        querys.put("param", "**code**:"+code+",**minute**:1");
        //smsSignId（短信前缀）和templateId（短信模板），可登录国阳云控制台自助申请。参考文档：http://help.guoyangyun.com/Problem/Qm.html
        querys.put("smsSignId", "2e65b1bb3d054466b82f0c9d125465e2");
        querys.put("templateId", "908e94ccf08b4476ba6c876d13f084ad");
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //获取response的code
            JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
            String codeValue = jsonObject.getString("code");
            System.out.println("发送短信验证码返回："+jsonObject.toJSONString());
            if (codeValue.equals("0")){
                return true;
            }else {
                return false;
            }
        } catch (Exception e) {
            System.out.println(e);
            return false;
        }
    }

    //获取redis里的验证码
    public static String checkCode(String phoneNum, int mode){
        Jedis jedis = new Jedis("localhost", 6379);
        String code = "none"; // 默认返回值

        // 获取存储的 JSON 字符串
        String jsonInfo = jedis.get(phoneNum+mode);

        if (jsonInfo != null) {
            JSONObject jsonObject = JSON.parseObject(jsonInfo);
            code = jsonObject.getString("verificationCode");
        }

        jedis.close();
        return code;
    }

    //api-注册 4-验证码错误 5-已注册 8-服务器响应失败 11-注册成功
    @Override
    public int signUp(String phoneNum, int mode, String code,String password) {
        List<AccountSt> accountStList = km.getAllAccountsByPhone(phoneNum);
        if (accountStList.size()>0){
            return 5;
        }
        if (!checkCode(phoneNum, mode).equals(code)){
            return 4;
        }else{
            try {
                //将注册账号写入数据库
                if (km.insertNewAccount(phoneNum,password)){
                    return 11;
                }
                return 8;
            }catch (Exception e){
                System.out.println(e);
                return 8;
            }
        }
    }

    //api-找回密码 4-验证码错误 6-手机号还未注册 9-服务器响应失败 12-更改密码成功
    @Override
    public int resetPassword(String phoneNum, int mode, String code, String newPassword) {
        List<AccountSt> accountStList = km.getAllAccountsByPhone(phoneNum);
        if (accountStList.size() == 0){
            return 6;
        }
        if (!checkCode(phoneNum, mode).equals(code)){
            return 4;
        }else{
            try {
                //将重设密码写入数据库
                if (km.resetPassword(phoneNum, newPassword)){
                    return 12;
                }
                return 9;
            }catch (Exception e){
                System.out.println(e);
                return 9;
            }
        }
    }

    @Override
    public int getAccountId(String phoneNum) {
        return km.getAccountId(phoneNum);
    }

}
